/* 
 * File:   cp.c
 * Author: llz
 *aim to practice four system calls:open read write close
 * 
 * Created on May 24, 2014, 12:52 AM
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>


#ifndef BUFSIZE
#define BUFSIZE 1024
#endif

/*
 * 
 */
extern int errno;
int input_fd;
int output_fd;
char buffer[BUFSIZE];

int main(int argc, char** argv) {
    if(argc!=3||strcmp(argv[1],"--help")==0){
        printf("%s oldfile newfile",argv[0]);
        return EXIT_FAILURE;
    }
    input_fd = open(argv[1],O_RDONLY);
    if (input_fd==-1) {
        perror("open error:");
    }

    int flags=O_RDWR|O_CREAT|O_APPEND;
    int mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
    output_fd = open(argv[2],flags,mode);
    if (output_fd) {
        strerror(errno);
    }
    
    /*begin copy*/
    ssize_t numRead;
    
    while((numRead = read(input_fd,buffer,BUFSIZE))>0){
        if (write(output_fd,buffer,numRead)!=numRead) { //read what write what
            printf("%s","cant copy all content");
        }
    }
    
    if(numRead == -1){
        perror("read error:");
    }
    //close
    
    if(close(input_fd)==-1){
        strerror(errno);
    }
    if(close(output_fd)==-1){
        perror("close error:");
    }
    return (EXIT_SUCCESS);
}

